package com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.operatelog.core.annotations.OperateLog;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.OptionVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.PreviewQuestionnaireInfo;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionnaireDetailVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionnaireInfoCreateVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionnairePageRespVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.questionnaireinfo.vo.QuestionnairePageVO;
import com.xiaoshuidi.cloud.module.member.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.member.excel.EasyWriteHandler;
import com.xiaoshuidi.cloud.module.member.excel.HeadContentCellStyle;
import com.xiaoshuidi.cloud.module.member.service.questionnaireinfo.MemberQuestionnaireInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xiaoshuidi.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;
import static com.xiaoshuidi.cloud.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.xiaoshuidi.cloud.module.member.enums.ErrorCodeConstants.COUPON_USED;
import static com.xiaoshuidi.cloud.module.member.enums.ErrorCodeConstants.NO_USER;

@Tag(name = "管理后台 - 问卷信息")
@RestController
@RequestMapping(ApiConstants.NAME + "/questionnaire-info")
@Validated
@Slf4j
public class MemberQuestionnaireInfoController {
    @Resource
    private MemberQuestionnaireInfoService memberQuestionnaireInfoService;

    @PostMapping("/create")
    @Operation(summary = "创建问卷")
    public CommonResult<Long> create(@Valid @RequestBody QuestionnaireInfoCreateVO createReqVO) {
        return success(memberQuestionnaireInfoService.create(createReqVO));
    }

    @PostMapping("/update")
    @Operation(summary = "需要改问卷")
    public CommonResult<Boolean> update(@Valid @RequestBody QuestionnaireInfoCreateVO createReqVO) {
        return success(memberQuestionnaireInfoService.update(createReqVO));
    }

    @GetMapping("/publish/{id}")
    @Operation(summary = "发布问卷")
    public CommonResult<Boolean> publish(@PathVariable("id") Long id) {
        return success(memberQuestionnaireInfoService.publish(id));
    }

    @PostMapping("/get-page")
    @Operation(summary = "获得问卷分页列表")
    public CommonResult<PageResult<QuestionnairePageRespVO>> getPage(@Valid @RequestBody QuestionnairePageVO pageVO) {
        PageResult<QuestionnairePageRespVO> pageResult = memberQuestionnaireInfoService.getPage(pageVO);
        return success(pageResult);
    }

    @GetMapping("/get-by-id/{id}")
    @Operation(summary = "查看问卷")
    public CommonResult<QuestionnaireDetailVO> getById(@PathVariable("id") Long id) {
        return success(memberQuestionnaireInfoService.getQuestionnaireById(id));
    }

    @GetMapping("/export-excel/{questionnaireId}")
    @Operation(summary = "导出问卷列表")
    public void exportExcel(HttpServletResponse response, @PathVariable("questionnaireId") Long questionnaireId) throws IOException, ClassNotFoundException {
        List<QuestionVO> questionList = memberQuestionnaireInfoService.getQuestionList(questionnaireId);
        List<List<String>> data = memberQuestionnaireInfoService.getQuestionnaireData(questionnaireId);
        if (CollectionUtils.isEmpty(data)) {
            throw exception(NO_USER);
        }
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            //构建主表头
            List<List<String>> headList = getFixedHeadLists();
            String fileName = URLEncoder.encode("问卷调查数据统计表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            for (int i = 1; i <= questionList.size(); i++) {
                QuestionVO questionVO = questionList.get(i - 1);
                List<OptionVO> optionList = questionVO.getOptionList();
                OptionVO option = new OptionVO();
                optionList.add(option);
                for (int j = 1; j <= optionList.size(); j++) {
                    List<String> head = new ArrayList<>();
                    head.add("问题" + i + "(" + questionVO.getTypeName() + ")");
                    if (j == 1) {
                        head.add("选项");
                    } else {
                        head.add("选项" + (j - 1));
                    }
                    headList.add(head);
                }
            }
            outputStream = response.getOutputStream();
            EasyExcel.write(outputStream)
                    .head(headList)
                    .inMemory(true)
                    .registerWriteHandler(HeadContentCellStyle.myHorizontalCellStyleStrategy())
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)) // 简单的列宽策略，列宽15
                    .registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 25, (short) 15)) // 简单的行高策略：头行高30，内容行高15
                    .registerWriteHandler(new EasyWriteHandler()).sheet("用户问卷数据").doWrite(data);
            ;
        } catch (IOException e) {
            log.error("导出失败------------" + e.getMessage());
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

    }

    @NotNull
    private List<List<String>> getFixedHeadLists() {
        List<List<String>> headList = new ArrayList<>();
        List<String> h1 = new ArrayList<>();
        h1.add("序号");
        h1.add("序号");
        headList.add(h1);
        List<String> h2 = new ArrayList<>();
        h2.add("姓名");
        h2.add("姓名");
        headList.add(h2);
        List<String> h3 = new ArrayList<>();
        h3.add("联系电话");
        h3.add("联系电话");
        headList.add(h3);
        List<String> h4 = new ArrayList<>();
        h4.add("年龄");
        h4.add("年龄");
        headList.add(h4);
        List<String> h5 = new ArrayList<>();
        h5.add("门店");
        h5.add("门店");
        headList.add(h5);
        List<String> h6 = new ArrayList<>();
        h6.add("性别");
        h6.add("性别");
        headList.add(h6);

        List<String> h7 = new ArrayList<>();
        h7.add("入住时长");
        h7.add("入住时长");
        headList.add(h7);
        return headList;
    }

    @GetMapping("/preview-questionnaire/{id}")
    @Operation(summary = "预览问卷")
    public CommonResult<PreviewQuestionnaireInfo> previewQuestionnaire(@PathVariable("id") Long id) {
        return success(memberQuestionnaireInfoService.previewQuestionnaire(id));
    }
}
